ARCH           ?= $(shell uname -m | sed s,i[3456789]86,ia32,)

EFIINC          = /usr/include/efi
EFIINCS         = -I$(EFIINC) -I$(EFIINC)/$(ARCH) -I$(EFIINC)/protocol
LIB             = /usr/lib
EFILIB          = /usr/lib
EFI_CRT_OBJS    = $(EFILIB)/crt0-efi-$(ARCH).o
EFI_LDS         = $(EFILIB)/elf_$(ARCH)_efi.lds

CFLAGS          = $(EFIINCS) -fno-stack-protector -fpic -fshort-wchar -mno-red-zone -Wall \
		-fno-strict-aliasing -nostdlib -fno-builtin
ifeq ($(ARCH),x86_64)
  CFLAGS += -DEFI_FUNCTION_WRAPPER
endif

LDFLAGS = -nostdlib -znocombreloc -T $(EFI_LDS) -shared -no-undefined -Bsymbolic -L $(EFILIB) -L $(LIB) $(EFI_CRT_OBJS)

all: hello.efi

efi: hello.efi
iso: hello.iso
test: hello.iso
	qemu-system-x86_64 \
		-machine pc \
		-accel kvm \
		-bios /usr/share/ovmf/x64/OVMF_CODE.fd \
		-net none \
		-m 1024 \
		-cdrom "$^"


hello.o: hello.c
	gcc $(CFLAGS) -c hello.c -o hello.o

hello.so: hello.o
	ld $(LDFLAGS) $^ -o $@ -lefi -lgnuefi

hello.efi: hello.so
	objcopy -j .text -j .sdata -j .data -j .dynamic \
		-j .dynsym  -j .rel -j .rela -j .reloc \
		--target=efi-app-$(ARCH) $^ $@

cache/isofs/efi.img: hello.efi
	mkdir -p cache
	dd if=/dev/zero of=cache/efi.img.tmp bs=512 count=5760
	mkfs.msdos -F 12 -n "HELLO" "cache/efi.img.tmp"
	mmd -i "cache/efi.img.tmp" ::EFI
	mmd -i "cache/efi.img.tmp" ::EFI/BOOT
	mcopy -i "cache/efi.img.tmp" "$^" ::EFI/BOOT/bootx64.efi
	#mcopy -i "cache/efi.img.tmp" "$^" ::hello.efi
	install -Dm644 "cache/efi.img.tmp" "$@"

hello.iso: cache/isofs/efi.img
	mkdir -p "cache/isofs"
	mkisofs -o "$@" \
		-R -J -d -N \
		-hide-rr-moved \
		-no-emul-boot \
		-eltorito-platform efi \
		-eltorito-boot "efi.img" \
		-V "HELLO" \
		"cache/isofs"

clean:
	rm -rf *.o *.efi *.so *.iso cache

